<?php
/**
 * @package YARBB
 * @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * YARBB! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
 */
// don't allow direct linking
defined( '_VALID_MOS' ) or die();

//запрет чтения форума группе
if ($yarbb_user['g_read_board'] == '0')

	mosRedirect(sefRelToAbs(YARBB_URL.'&amp;task=access&amp;action=noperm'));
	
mosCommonHTML::loadJquery();
//редактор бб кода
$mainframe->addJS($yarbb_live.'/theme/'.$yarbb_config['o_default_style'].'/plugins/markitup/jquery.markitup.js'); 
$mainframe->addJS($yarbb_live.'/theme/'.$yarbb_config['o_default_style'].'/plugins/markitup/sets/default/set.js');
$mainframe->addCSS($yarbb_live.'/theme/'.$yarbb_config['o_default_style'].'/plugins/markitup/skins/markitup/style.css');
$mainframe->addCSS($yarbb_live.'/theme/'.$yarbb_config['o_default_style'].'/plugins/markitup/sets/default/style.css');
// конец загрузки редактора

//парсер
require_once $yarbb_path.'/plugins/nbbc_custom.php';

$id = intval(mosGetParam($_GET, 'id', 0))  ;
if ($id < 1)
	mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);

// Fetch some info about the post, the topic and the forum
$sql = ('SELECT f.id AS fid, f.forum_name, f.moderators, f.redirect_url, fp.post_replies, fp.post_topics, t.id AS tid, t.subject, t.descrip_t, t.posted, t.closed, t.labels, t.icon_topic, p.poster, p.poster_id, p.message, p.hide_smilies 
					FROM #__forum_posts AS p 
					INNER JOIN #__forum_topics AS t ON t.id=p.topic_id 
					INNER JOIN #__forum_forums AS f ON f.id=t.forum_id 
					LEFT JOIN #__forum_forum_perms AS fp ON (fp.forum_id=f.id 
					AND fp.group_id='.$yarbb_user['g_id'].') 
					WHERE (fp.read_forum IS NULL OR fp.read_forum=1) 
					AND p.id='.$id);
$database->setQuery($sql);
$cur_post = $database->loadAssocList();
$cur_post = $cur_post[0];
if (!$cur_post)
	mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);


// Sort out who the moderators are and if we are currently a moderator (or an admin)
$mods_array = ($cur_post['moderators'] != '') ? unserialize($cur_post['moderators']) : array();
$is_admmod = ($yarbb_user['g_id'] == YARBB_ADMIN || ($yarbb_user['g_id'] == YARBB_MOD && array_key_exists($yarbb_user['username'], $mods_array)) || $yarbb_user['g_global_moderation']) ? true : false;

// Determine whether this post is the "topic post" or not
$sql =('SELECT id 
			FROM #__forum_posts 
			WHERE topic_id='.$cur_post['tid'].' 
			ORDER BY posted LIMIT 1');
$database->setQuery($sql);
$topic_post_id = $database->loadResult();

$can_edit_subject = ($id == $topic_post_id && (($yarbb_user['g_edit_subjects_interval'] == '0' || (time() - $cur_post['posted']) < $yarbb_user['g_edit_subjects_interval']) || $is_admmod)) ? true : false;

// Do we have permission to edit this post?
if (($yarbb_user['g_edit_posts'] == '0' ||
				$cur_post['poster_id'] != $yarbb_user['id'] ||
				$cur_post['closed'] == '1') && !$is_admmod)

	mosRedirect(sefRelToAbs(YARBB_URL), _NOT_AUTH);

// Start with a clean slate
$errors = array();
if (isset($_POST['form_sent'])) {
	if ($is_admmod)
	// If it is a topic it must contain a subject
		if ($can_edit_subject) {
			$subject = yarbb_trim($_POST['req_subject']);
			$descrip_t = yarbb_trim($_POST['descrip_t']);
			if ($subject == '')
				$errors[] = _Y_YANOVSUBJ;
			else if (yarbb_strlen($subject) > 100)
				$errors[] = _Y_YANOVSUBJ2;
			else if ($yarbb_config['p_subject_all_caps'] == '0' && strtoupper($subject) == $subject && ($yarbb_user['g_id'] > YARBB_MOD && !$yarbb_user['g_global_moderation']))
				$subject = ucwords(strtolower($subject));
			// If it is a topic it may contain a search labels
			$labels = yarbb_trim((isset($_POST['unreq_labels']))? $_POST['unreq_labels']: '');
			// cleanup string
			$labels = implode_labels( explode_labels($labels) );
		}
	// Clean up message from POST
	$message = yarbb_linebreaks(yarbb_trim($_POST['req_message']));
	if ($message == '')
		$errors[] = _Y_YANOMESS;
	else if (strlen($message) > 65535)
		$errors[] = _Y_YARLONGMESSAG;
	else if ($yarbb_config['p_message_all_caps'] == '0' && strtoupper($message) == $message && ($yarbb_user['g_id'] > YARBB_MOD && !$yarbb_user['g_global_moderation']))
		$message = ucwords(strtolower($message));
	// Validate BBCode syntax
	/*if ($yarbb_config['p_message_bbcode'] == '1' && strpos($message, '[') !== false && strpos($message, ']') !== false) {
		require $yarbb_path.'/plugins/parser.php';
		$message = preparse_bbcode($message, $errors);
	}*/
	$hide_smilies = isset($_POST['hide_smilies']) ? intval($_POST['hide_smilies']) : 0;
	if ($hide_smilies != '1') $hide_smilies = '0';
	// Did everything go according to plan?
	if (empty($errors) && !isset($_POST['preview'])) {
		$edited_sql = (!isset($_POST['silent']) || !$is_admmod) ? $edited_sql = ', edited='.time().', edited_by=\''.$database->getEscaped($yarbb_user['username']).'\'' : '';
		require $yarbb_admin_path.'/include/search_idx.php';
		if ($can_edit_subject) {
			$sql = ('UPDATE #__forum_topics
							SET subject=\''.$database->getEscaped($subject).'\', 
							descrip_t=\''.$database->getEscaped($descrip_t).'\', 
							labels=\''.$database->getEscaped($labels).'\'  
							WHERE id='.$cur_post['tid'].' 
							OR moved_to='.$cur_post['tid']);
			$database->setQuery($sql);
			$database->Query();
			// We changed the subject, so we need to take that into account when we update the search words
			update_search_index('edit', $id, $message, $subject);
		}
		else
			update_search_index('edit', $id, $message);

		// Update the post
		$sql =('UPDATE #__forum_posts
							SET message=\''.$database->getEscaped($message).'\', 
							hide_smilies=\''.$hide_smilies.'\''.$edited_sql.' 
							WHERE id='.$id);
		$database->setQuery($sql);
		$database->Query();

		mosRedirect(sefRelToAbs(YARBB_URL.'&amp;task=viewtopic&amp;pid='.$id.'#p'.$id));

	}
}
echo $mainframe->setPageTitle( _EDIT_CATEGORY );

$required_fields = array('req_subject' => _HEADER, 'req_message' => _Y_MESSAGE);
$focus_element = array('edit', 'req_message');
$cur_index = 1;
?>
<script language="javascript">
	<!--
	function PopUp(url, titre, largeur, hauteur, options)
	{
		var top=(screen.height-hauteur)/3;
		var left=(screen.width-largeur)/2;
		window.open(url, titre, "top="+top+", left="+left+", width="+largeur+", height="+hauteur+", "+options);
	}
	-->
</script>

<div class="linkst">
	<div class="inbox">
		<ul>
			<li><a href="<?php echo sefRelToAbs(YARBB_URL) ?>"><?php echo _Y_INDEX; ?></a></li>
			<li>&nbsp;&raquo;&nbsp;<a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=viewforum&amp;id='.$cur_post['fid']); ?>"><?php echo yarbb_htmlspecialchars($cur_post['forum_name']) ?></a></li>
			<li>&nbsp;&raquo;&nbsp;<?php echo yarbb_htmlspecialchars($cur_post['subject']) ?></li>
		</ul>
	</div>
</div>
<?php
// If there are errors, we display them
if (!empty($errors)) {
	?>
<div id="posterror" class="block">
	<h2><span><?php echo _Y_YARERROR; ?></span></h2>
	<div class="box">
		<div class="inbox">
			<p><?php echo _Y_YARERRORINF; ?></p>
			<ul>
	<?php
	while (list(, $cur_error) = each($errors))
		echo "\t\t\t\t".'<li><strong>'.$cur_error.'</strong></li>'."\n";
	?>
			</ul>
		</div>
	</div>
</div>
					<?php
				}
else if (isset($_POST['preview'])) {
	
	$preview_message = $bbcode->Parse($message, $hide_smilies);
	?>
<div id="postpreview" class="blockpost">
	<h2><span><?php echo _PREVIEW; ?></span></h2>
	<div class="box">
		<div class="inbox">
			<div class="postright">
				<div class="postmsg"> <?php echo $preview_message."\n" ?> </div>
			</div>
		</div>
	</div>
</div>
	<?php
}
?>
<div class="blockform">
	<h2><?php echo _EDIT_CATEGORY; ?></h2>
	<div class="box">
		<form id="edit" method="post" action="<?php echo YARBB_URL?>&amp;task=edit&amp;id=<?php echo $id?>&amp;action=edit" <?php echo 'enctype="multipart/form-data"';  ?> onsubmit="return process_form(this)" enctype="multipart/form-data">
			<div class="inform">
				<fieldset>
					<legend><?php echo _Y_YAREDITINFO; ?></legend>
					<input type="hidden" name="form_sent" value="1" />
					<div class="infldset txtarea">
<?php if ($can_edit_subject) {
	?>
						<label><?php echo _CAPTION; ?><br />
							<input class="longinput" type="text" name="req_subject" size="80" maxlength="70" tabindex="<?php echo $cur_index++ ?>" value="<?php echo yarbb_htmlspecialchars(isset($_POST['req_subject']) ? $_POST['req_subject'] : $cur_post['subject']) ?>" />
							<br />
						</label>
						<label><?php echo _DESCRIPTION; ?><br />
							<input class="longinput" type="text" name="descrip_t" value="<?php echo yarbb_htmlspecialchars(isset($_POST['descrip_t']) ? $_POST['descrip_t'] : $cur_post['descrip_t']); ?>" size="80" maxlength="70" tabindex="<?php echo $cur_index++ ?>" />
							<br />
						</label>
	<?php }else { ?>
	<?php echo _Y_TIMEEDITNON; ?>
						<label><?php echo _CAPTION; ?><br />
							<input name="req_subject" type="text" class="longinput" tabindex="<?php echo $cur_index++ ?>" value="<?php echo yarbb_htmlspecialchars(isset($_POST['req_subject']) ? $_POST['req_subject'] : $cur_post['subject']) ?>" size="80" maxlength="70" readonly="true" />
							<br />
						</label>
						<label><?php echo _DESCRIPTION; ?><br />
							<input name="descrip_t" type="text" class="longinput" tabindex="<?php echo $cur_index++ ?>" value="<?php echo yarbb_htmlspecialchars(isset($_POST['descrip_t']) ? $_POST['descrip_t'] : $cur_post['descrip_t']); ?>" size="80" maxlength="70" readonly="true" />
							<br />
						</label>
	<?php
}
$bbcode_form = 'edit'; 
$bbcode_field = 'req_message'; 
?>
<script type="text/javascript">
<!--
$(document).ready(function()	{
	// Add markItUp! to your textarea in one line
	// $('textarea').markItUp( { Settings }, { OptionalExtraSettings } );
	$('#req_message').markItUp(mySettings);
	
	// You can add content from anywhere in your page
	// $.markItUp( { Settings } );	
	$('.add').click(function() {
 		$.markItUp( { 	openWith:'<opening tag>',
						closeWith:'<\/closing tag>',
						placeHolder:"New content"
					}
				);
 		return false;
	});
	
	// And you can add/remove markItUp! whenever you want
	// $(textarea).markItUpRemove();
	$('.toggle').click(function() {
		if ($("#req_message.markItUpEditor").length === 1) {
 			$("#req_message").markItUpRemove();
			$("span", this).text("get markItUp! back");
		} else {
			$('#req_message').markItUp(mySettings);
			$("span", this).text("remove markItUp!");
		}
 		return false;
	});
	
	    $('#emoticons a').click(function() {
        emoticon = $(this).attr("title");
        $.markItUp( { replaceWith:emoticon } );
    });
});
-->
</script>
						<label><?php echo _Y_MESSAGE; ?><br />
<div id="emoticons">
    <?php
	
// Display the smiley set
$smiley_dups = array();
$num_smilies = count($smiley_text);
for ($i = 0; $i < $num_smilies; ++$i)
{
	// Is there a smiley at the current index?
	if (!isset($smiley_text[$i]))
		continue;
	if (!in_array($smiley_img[$i], $smiley_dups))
		echo "\t\t\t\t\t\t\t".'<a href="#" title=" '.$smiley_text[$i].' "><img src="'.$yarbb_live.'/images/smilies/'.$smiley_img[$i].'" alt="'.$smiley_text[$i].'" /></a>'."\n";
	$smiley_dups[] = $smiley_img[$i];
}
?>
</div>
							<textarea name="req_message" id="req_message" tabindex="<?php echo $cur_index++ ?>"><?php echo yarbb_htmlspecialchars(isset($_POST['req_message']) ? $message : $cur_post['message']) ?></textarea>
							<br />
						</label>
						<?php if ($can_edit_subject) {
							if (!empty($yarbb_config['o_topic_labels'])) {
								?>
						<label><?php echo $lang_common['Labels'] ?><br />
							<input class="longinput" type="text" name="unreq_labels" size="80" maxlength="70" tabindex="<?php echo $cur_index++ ?>" value="<?php echo yarbb_htmlspecialchars(substr($cur_post['labels'],1,-1)) ?>" />
							<br />
						</label>
		<?php
							} else {
								?>
						<input class="longinput" type="hidden" name="unreq_labels" value="<?php echo yarbb_htmlspecialchars(substr($cur_post['labels'],1,-1)) ?>" />
								<?php
	}
}
?>
					</div>
				</fieldset>
						<?php
						$checkboxes = array();
if ($yarbb_config['o_smilies'] == '1') {
							if (isset($_POST['hide_smilies']) || $cur_post['hide_smilies'] == '1')
								$checkboxes[] = '<label><input type="checkbox" name="hide_smilies" value="1" checked="checked" tabindex="'.($cur_index++).'" />&nbsp;'._Y_YARSMILEHID;
							else
								$checkboxes[] = '<label><input type="checkbox" name="hide_smilies" value="1" tabindex="'.($cur_index++).'" />&nbsp;'._Y_YARSMILEHID;
}
if ($is_admmod) {
					if ((isset($_POST['form_sent']) && isset($_POST['silent'])) || !isset($_POST['form_sent']))
						$checkboxes[] = '<label><input type="checkbox" name="silent" value="1" tabindex="'.($cur_index++).'" checked="checked" />&nbsp;'._Y_YANOSELENT;
					else
						$checkboxes[] = '<label><input type="checkbox" name="silent" value="1" tabindex="'.($cur_index++).'" />&nbsp;'._Y_YANOSELENT;
				}
				if (!empty($checkboxes)) {
					?>
			</div>
			<div class="inform">
				<fieldset>
					<legend><?php echo _Y_YAROTIONS; ?></legend>
					<div class="infldset">
						<div class="rbox"> <?php echo implode('</label>'."\n\t\t\t\t\t\t\t", $checkboxes).'</label>'."\n";?> </div>
					</div>
				</fieldset>
					<?php
				}
				?>
			</div>
			<input type="submit" name="submit" value="<?php echo _SUBMIT_BUTTON; ?>" tabindex="<?php echo $cur_index++ ?>" accesskey="s" />
			<input name="" type="button" onclick="javascript:PopUp('<?php echo YARBB_URL ?>&amp;task=gestionnaire', 'gest', '850', '530', 'resizable=yes, location=no, menubar=no, status=no, scrollbars=yes')" value="<?php echo _Y_YARATTACHFILE; ?>" />
			<input type="submit" name="preview" value="<?php echo _PREVIEW; ?>" tabindex="<?php echo $cur_index++ ?>" accesskey="p" />
			<input name="" type="button" onclick="javascript:history.go(-1)" value="<?php echo _CANCEL; ?>" />
		</form>
	</div>
</div>
